var MAX_NUM_SEL = 100;

var g_keyseq = '';
var g_n_match = 0;
var g_selections = new Array();


if (!Array.prototype.jsime_filter)
{

  // using binary search to speed up
  function look_for_start(s) {
    find = -1, low = 0, mid = 0, high = imetable.length;
    s_key = "";
      while(low < high) {
        mid = (low + high) / 2;
        mid = Math.floor(mid);
        s_key = imetable[mid][0];
        if(s_key.indexOf(s,0) == 0) { find = mid; break; }
        s_key = imetable[mid-1][0];
        if(s_key.indexOf(s,0) == 0) { find = mid; break; }
        if(s_key < s) { low = mid + 1; } else { high = mid - 1; }
      }
      while(find > 0) {
        s_key = imetable[find - 1][0];
        if(s_key.indexOf(s,0) == 0) { find = find - 1; } else { break; }
      }
      // window.status = "Found: " + find;
      return(find);
  }

  Array.prototype.jsime_filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    g_n_match = 0;
    for (var i = look_for_start(g_keyseq); i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this)) {
          res.push(val);
          // window.status = "Matched: " + i;
	  if (g_n_match > MAX_NUM_SEL) return res;
        } else {
          // window.status = "At: " + i + ": " + imetable[i][0] + " / " + g_n_match;
	  // already match, we can return now (provided the imetable is ordered
          return res;
	}
      }
    }

    return res;
  };
}

function select_char(element, index, array) {  
  if (index <= 0) g_n_match = 0;
  if ( g_n_match > MAX_NUM_SEL ) return false;
  var regex = new RegExp('^'+g_keyseq+'.*$', 'i');
  if (regex.test(element[0])) {
    g_n_match = g_n_match + element.length - 1;
    return true;
  };
  return false;  
} 

function jsime_get_selection(keyseq) {
  var a_selections = new Array();
  var a_temp_sel = new Array();
  var a_temp = new Array();
    if (keyseq.length <= 0) {
       g_keyseq = '';
       g_selections = [];
       return;
    }
    g_keyseq = keyseq;
    a_selections = imetable.jsime_filter(select_char);
    // clear g_selections
    g_selections = [];
    var j = 0;
    for ( var k = 0; k < a_selections.length; k++ ) {
      a_temp_sel = [];
      a_temp_sel = a_temp_sel.concat(a_selections[k]);
      if (g_keyseq.length < a_temp_sel[0].length) {
        // append suffix to selections
        var suffix = '';
        var s_temp = a_temp_sel[0];
        suffix = s_temp.slice(g_keyseq.length);
        for (var i = 1; i < a_temp_sel.length; i++) 
          a_temp_sel[i] = a_temp_sel[i] + suffix;
      } 
      a_temp_sel.shift();
      a_temp = g_selections.concat(a_temp_sel);
      g_selections = [];
      g_selections = a_temp;
      j = j + a_temp_sel.length;
      if (j > MAX_NUM_SEL) return;
    }
}
